<template>
  <div class="course-detail">
    <el-skeleton :rows="5" animated v-if="loading" />
    <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" />
    <div v-else>
      <el-page-header @back="$router.go(-1)">
        <template #content>
          <span class="course-title">{{ course.title }}</span>
        </template>
      </el-page-header>

      <el-card class="box-card" v-if="course.description"
        style="margin-top: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);">
        <div v-html="course.description"></div>
        <el-progress v-show="loggedIn" :text-inside="true" :stroke-width="26" status="success"
          :percentage="courseProgress"></el-progress>
      </el-card>

      <div class="lessons-list">
        <h2>课时</h2>
        <el-empty v-if="lessons.length === 0" description="No lessons available for this course" />
        <el-row v-else :gutter="20">
          <el-col v-for="(lesson, index) in lessons" :key="lesson.id" :xs="24" :span="8" style="margin-bottom: 20px;">
            <el-card class="lesson-card" :class="'lesson-card-' + (index % 6 + 1)" shadow="hover">
              <template #header>
                <div class="lesson-title">{{ lesson.order }}. {{ lesson.title }}</div>
              </template>
              <div v-if="lesson.description" class="lesson-description">
                {{ lesson.description }}
              </div>
              <!-- Completion status icon and study time -->
              <div class="status-info">
                <el-icon v-if="lesson.progress && lesson.progress.is_completed" class="completed-icon">
                  <Check />
                </el-icon>
                <el-icon v-else class="in-progress-icon">
                  <Clock />
                </el-icon>
                <el-progress style="width:100%;" :text-inside="true" :stroke-width="loggedIn ? 26 : 0" status="success"
                  :percentage="(lesson.progress && lesson.progress.completion_percentage) || 0"></el-progress>
                <el-button v-if="lesson.progress && !lesson.progress.is_completed" type="warning"
                  @click="continueStudy(lesson)" class="continue-btn">
                  继续
                </el-button>
                <el-button v-if="!lesson.progress || lesson.progress.is_completed" type="primary"
                  @click="$router.push(`/lesson/${encodeURIComponent(course.path)}/${lesson.id}`)">
                  学习
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import http from '@/utils/http'
import { isLoggedIn } from '@/utils/auth'
import { ElSkeleton, ElAlert, ElPageHeader, ElCard, ElRow, ElCol, ElButton, ElEmpty, ElIcon } from 'element-plus'
import { Check, Clock } from '@element-plus/icons-vue'

export default {
  name: 'CourseDetail',
  components: {
    ElSkeleton,
    ElAlert,
    ElPageHeader,
    ElCard,
    ElRow,
    ElCol,
    ElButton,
    ElEmpty,
    ElIcon,
    Check,
    Clock
  },
  data() {
    return {
      course: null,
      lessons: [],
      loading: true,
      error: null,
      courseProgress: 0,
      loggedIn: false
    }
  },
  async mounted() {
    const courseId = this.$route.params.id
    await this.loadCourseDetails(courseId)
    this.loggedIn = isLoggedIn()
  },
  methods: {
    async loadCourseDetails(courseId) {
      try {
        // Load course details
        const courseResponse = await http.get(`/courses/${courseId}`)
        this.course = courseResponse

        // Load lessons for this course
        const lessonsResponse = await http.get(`/courses/${courseId}/lessons`)
        this.lessons = lessonsResponse

        this.loading = false
        // Load progress for all lessons in this course
        try {
          if (!isLoggedIn()) {
            return;
          }
          const lessonProgress = await http.get(`/progress/lessons?course_path=${this.course.path}`)

          // Create a map of lesson progress by lesson path
          const progressMap = {}
          lessonProgress.forEach(progress => {
            progressMap[progress.lesson_id] = progress
          })
          let lessonProcess = 0;
          const totleLessons = this.lessons.length;
          // Attach progress to each lesson
          this.lessons.forEach(lesson => {
            if (progressMap[lesson.id]) {
              lesson.progress = progressMap[lesson.id]
              lesson.progress
                && lesson.progress.completion_percentage
                && (lesson.progress.completion_percentage = Math.floor(lesson.progress.completion_percentage))
                && (lessonProcess += lesson.progress.completion_percentage / 100.0);
            }
          })
          const percentage = lessonProcess / totleLessons;
          let percentage100 = (percentage > 0.99 && percentage < 1) ? 99 : Math.floor(percentage * 100);
          if (lessonProcess > 0 && percentage100 === 0) percentage100 = 1;
          this.courseProgress = percentage100;
        } catch (progressErr) {
          console.warn('Failed to load lesson progress:', progressErr)
        }

      } catch (err) {
        this.error = 'Failed to load course details'
        this.loading = false
        console.error(err)
      }
    },

    formatTime(seconds) {
      const hours = Math.floor(seconds / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      const secs = seconds % 60

      if (hours > 0) {
        return `${hours}h ${minutes}m ${secs}s`
      } else if (minutes > 0) {
        return `${minutes}m ${secs}s`
      } else {
        return `${secs}s`
      }
    },

    continueStudy(lesson) {
      this.$router.push(`/lesson/${encodeURIComponent(this.course.path)}/${lesson.id}`)
    }
  }
}
</script>

<style scoped>
.course-detail {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.course-title {
  font-size: 1.5rem;
  font-weight: bold;
}

.lesson-title {
  font-weight: bold;
  color: #333;
  font-size: 1.1em;
  text-overflow: ellipsis;
  text-wrap-mode: nowrap;
  overflow: hidden;
}

.lesson-description {
  color: #666;
  font-size: 0.9em;
  text-overflow: ellipsis;
  text-wrap-mode: nowrap;
  overflow: hidden;
}

.lesson-meta {
  margin-top: 10px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 10px 0;
}

.completed-icon {
  color: #67c23a;
  font-size: 1.2em;
}

.in-progress-icon {
  color: #e6a23c;
  font-size: 1.2em;
}

.time-spent {
  font-size: 0.9em;
  color: #909399;
}

.continue-btn {
  margin-right: 10px;
  background-color: #e6a23c;
  border-color: #e6a23c;
}

.lessons-list h2 {
  color: #333;
  padding-bottom: 10px;
  margin-bottom: 10px;
  text-align: center;
  font-size: 2rem;
}

.lesson-card {
  border-radius: 10px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-repeat: no-repeat;
  background-position: 80% bottom;
  background-size: auto 80%;
  overflow: hidden;
  position: relative;
}

.lesson-card-1 {
  background-image: url('/assets/images/silhouette-danse-02.svg');
  background-color: #fff3e0;
}

.lesson-card-2 {
  background-image: url('/assets/images/silhouette-danse-04.svg');
  background-color: #e3f2fd;
}

.lesson-card-3 {
  background-image: url('/assets/images/silhouette-danse-05.svg');
  background-color: #f3e5f5;
}

.lesson-card-4 {
  background-image: url('/assets/images/silhouette-danse-06.svg');
  background-color: #e8f5e9;
}

.lesson-card-5 {
  background-image: url('/assets/images/silhouette-danse-07.svg');
  background-color: #f5f5f5;
}

.lesson-card-6 {
  background-image: url('/assets/images/silhouette-danse-08.svg');
  background-color: #fff3e0;
}

.lesson-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15) !important;
}

@media (max-width: 768px) {
  .course-title {
    font-size: 1rem;
  }
}
</style>